<template>
  <el-card class="box-card" style="overflow: hidden;overflow-x: scroll;overflow-y: scroll; height: 100%" ref="cardView">
    <!-- 尺寸 -->
    <div style="display: flex; align-items: center; justify-content: space-between;min-width: 800px;">
      <span style="display: flex">
        <span style="flex-shrink: 0; margin: 10px 0">尺寸：</span>
        <a-space size="middle" wrap style="flex-wrap: wrap">
          <div
            v-for="item in sizeList"
            :key="item.text"
            style="cursor: pointer; margin: 10px 0"
            @click="handleTemplateSizeChange(item)"
          >
            <span v-if="queryParam.templateSize == item.value" class="highLight">{{ item.text }}</span>
            <span v-else style="padding: 4px 10px">{{ item.text }}</span>
          </div>
        </a-space>
      </span>
      <span style="display: flex">
        <a-input
          v-model="queryParam.searchValue"
          placeholder="请输入关键字搜索"
          style="width: 200px; margin-right: 10px"
          allowClear
        />
        <a-button type="primary" @click="getTableData()">搜索</a-button>
      </span>
    </div>
    <!-- 行业 -->
    <div style="display: flex;min-width: 800px;" :style="industryMore ? '' : 'height: 38px;overflow: hidden;'">
      <span style="flex-shrink: 0; margin: 10px 0">行业：</span>
      <a-space size="middle" wrap style="flex-wrap: wrap">
        <div
          v-for="item in industryList"
          :key="item.value"
          style="cursor: pointer; margin: 10px 0"
          @click="handleIndustryChange(item)"
        >
          <span v-if="queryParam.templateIndustry == item.value" class="highLight">{{ item.text }}</span>
          <span v-else style="padding: 4px 10px; margin: 10px 0">{{ item.text }}</span>
        </div>
      </a-space>
      <span
        style="flex-shrink: 0; margin: 10px 0; color: #1a93fa; cursor: pointer"
        @click="industryMore = !industryMore"
        >{{ industryMore ? '收回' : '展开' }}</span
      >
    </div>

    <!-- 分类 -->
    <div style="display: flex;min-width: 800px;" :style="typeMore ? '' : 'height: 38px;overflow: hidden;'">
      <span style="flex-shrink: 0; margin: 10px 0">分类：</span>
      <a-space size="middle" wrap style="flex-wrap: wrap">
        <div
          v-for="item in orderTypes"
          :key="item"
          style="cursor: pointer; margin: 10px 0"
          @click="handleTypeChange(item)"
        >
          <span v-if="queryParam.templateType == item" class="highLight">{{ item }}</span>
          <span v-else style="padding: 4px 10px; margin: 10px 0">{{ item }}</span>
        </div>
      </a-space>
      <span v-if="orderTypes.length > 5" style="flex-shrink: 0; margin: 10px 0; color: #1a93fa; cursor: pointer" @click="typeMore = !typeMore">{{
        typeMore ? '收回' : '展开'
      }}</span>
    </div>
    <!-- 模板列表 -->
    <div ref="" style="display: flex; flex-wrap: wrap; min-width: 800px;" v-if="tableData.length > 0">
      <div
        v-for="item in tableData"
        :key="item.id"
        class="template-item"
        :style="{'width': itemWidth, 'height': itemWidth == '20%' ? '250px' : '200px'}"
      >
        <div class="template-item-content" @mouseenter="activeId = item.id"
        @mouseleave="activeId = ''" :style="activeId == item.id ? 'border: #1A93FA solid 3px;border-radius:14px;' : 'border: #999 solid 1px;'">
          <img
            v-if="item.templatePreview"
            :src="item.templatePreview"
            class="template-img"
            @load="imageLoad($event, item)"
          />
          <div v-show="activeId && activeId == item.id" class="template-mask">
            <div style="padding: 10px; margin-right: 15px" @click="handlePreview(item)">预览</div>
            <div style="padding: 10px; margin-left: 15px" @click="handleUse(item)" v-if="!item.isPurchased">使用</div>
          </div>
          <div class="template-desc">
            <div style="text-align: center">编号：{{ item.templateNumber }}</div>
            <div class="text">介绍：{{ item.templateDesc }}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 分页组件 -->
    <div style="width: 100%; text-align: center; margin-top: 20px" v-if="tableData.length > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, jumper, prev, pager,next, sizes"
        :total="templateTotal"
      ></el-pagination>
    </div>
    <div v-if="tableData.length == 0" style="text-align: center; padding: 80px; color: #999">无相关结果</div>
    <!-- 模板图片预览 -->
    <a-modal
      :visible="previewVisible"
      title=""
      :width="previewWidth || 1000"
      :footer="null"
      @cancel="previewVisible = false"
    >
      <img :src="previewSrc" :style="{ 'max-width': previewWidth - 50 + 'px' }" />
    </a-modal>
    <!-- 购买弹窗 -->
    <a-modal
      :visible="buyInfo.visible"
      :title="buyInfo.title"
      :footer="null"
      width="460px"
      @cancel="handleBuyCancel"
      :maskClosable="false"
      :keyboard="false"
    >
      <!-- //showType 1(有免费次数) 2（购买）3（购买成功）
        //haveFree 是否有免费使用个数 -->
      <div style="display: flex; justify-content: center; padding: 20px 10px; font-family: 'PingFang SC-Regular'">
        <div v-if="buyInfo.showType == 1" style="width: 300px; line-height: 30px; text-align: left; height: 200px">
          <div>您的免费使用模板次数剩余：{{ buyInfo.freeCountUsage }}个</div>
          <div>使用完，其他模板需要另外付费</div>
          <div style="margin: 20px 0">
            模板使用费<span style="font-size: 24px; color: #fd6c21; font-weight: 600; margin-left: 10px"
              >{{ buyInfo.price }}元</span
            ><span style="color: #fd6c21; font-weight: 600">/个</span>
          </div>
          <span class="highLight" style="padding: 5px 10px; margin-top: 20px" @click="handleAddOrder(3)"
            >免费使用（剩余{{ buyInfo.freeCountUsage }}个)</span
          >
        </div>
        <div
          v-if="buyInfo.showType == 2"
          style="width: 100%; display: flex; justify-content: space-between; align-items: center"
        >
          <div style="">
            <div v-if="buyInfo.haveFree">您的免费模板次数已用完<br />使用此模板需要另外付费</div>
            <div style="margin: 20px 0">
              模板使用费<span style="font-size: 24px; color: #fd6c21; font-weight: 600; margin-left: 10px"
                >{{ buyInfo.price }}元</span
              ><span style="color: #fd6c21; font-weight: 600">/个</span>
            </div>
          </div>
          <div>
            <div id="qqq" style="display: flex; justify-content: center; width: 120px; height: 120px">
              <div style="margin: 0 auto" id="qrcode1" ref="qrCodeUrl1"></div>
            </div>
            <div style="text-align: center; margin-top: 10px">请扫码支付</div>
          </div>
        </div>
        <div v-if="buyInfo.showType == 3">
          <div style="display: flex; align-items: center">
            <img src="@assets/template.png" style="width: 42px; height: 42px" />
            <div style="font-size: 12px; margin-left: 12px">您已购买成功，<br />模版已加入到您的模块库里。</div>
          </div>
          <a-space size="middle" style="margin-top: 30px; margin-left: 30px">
            <a-button type="primary" @click="buyInfo.visible = false">确定</a-button>
            <a-button @click="buyInfo.visible = false">取消</a-button>
          </a-space>
        </div>
      </div>
    </a-modal>
  </el-card>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'
import QRCode from 'qrcodejs2'
import { handleIsBaseVersion } from '@/utils/index'
import Vue from 'vue'
export default {
  name: 'templateSet',
  components: {},
  data() {
    return {
      queryParam: {
        templateSize: '',
        templateIndustry: '',
        templateType: '全部',
        searchValue: '',
      },
      pageSize: 10, //每页的数据条数
      currentPage: 1, //默认开始页面
      templateTotal: 0,
      tableData: [],
      industryList: [],
      industryMore: false,
      typeMore: false,
      activeId: '',
      previewVisible: false,
      previewSrc: '',
      previewWidth: 800,
      useCountData: {}, //价格、使用次数
      sizeList: [
        { text: '全部', value: '' },
        { text: 'A4二等分(竖向)', value: 'A4二等分（竖向）' },
        { text: 'A4三等分(竖向)', value: 'A4三等分（竖向）' },
        { text: 'A4不分页(竖向)', value: 'A4不分页（竖向）' },
        { text: 'A4二等分(横向)', value: 'A4二等分（横向）' },
        { text: 'A4不分页(横向)', value: 'A4不分页（横向）' },
      ],
      orderTypes: [
        '全部',
        '销售出库单',
        '销售退货单',
        '销售换货单',
        '销售订单',
        '采购入库单',
        '采购退货单',
        '采购换货单',
        '采购订单',
        '收款结算单',
        '付款结算单',
        '一般费用单',
        '其他收入单',
        '转账单',
        '物流代收结算单',
        '物流代付结算单',
        '物流运费结算单',
        '盘点单',
        '调拨单同价调拨',
        '调拨单变价调拨',
        '报损单',
        '报溢单',
        '成本调整单',
        '其他入库单',
        '其他出库单',
        '期初库存录入',
        '库存调整单',
        '资金增加',
        '资金减少',
        '应收款增加',
        '应收款减少',
        '应付款增加',
        '应付款减少',
      ],
      buyInfo: {
        visible: false,
        title: '使用模板',
        showType: 1,
        price: 0,
        freeCount: 0,
      },
      activeTemplate: {},
      orderModel: {},
      timer: null,
      widths: {},
      itemWidth: '25%'
    }
  },
  created() {
    if (handleIsBaseVersion()) {
      this.orderTypes = [
        '全部',
        '销售出库单',
        '销售退货单',
        '销售换货单',
        // '其他出库单',
      ]
    }
    let list = getDictItemsFromCache('template_industry')
    this.industryList = [
      {
        value: '',
        text: '全部',
      },
    ].concat(list)
    this.getTableData()
    console.log(this.orderTypes.length);
    
  },
  watch: {
    previewWidth(val) {
      console.log('-------', val)
    },
  },
  mounted() {
    this.handleResize()
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize(e) {
      let dom = this.$refs.cardView
      if (dom && dom.$el) {
        let w = dom.$el.clientWidth
        this.itemWidth = w > 1100 ? '20%' : '25%'
      } else {
        this.itemWidth = '25%'
      }
    },
    handleTemplateSizeChange(item) {
      this.queryParam.templateSize = item.value
      this.getTableData()
    },
    handleIndustryChange(item) {
      this.queryParam.templateIndustry = item.value
      this.getTableData()
    },
    handleTypeChange(item) {
      this.queryParam.templateType = item
      this.getTableData()
    },
    imageLoad(event, item) {
      console.log('imageLoad')

      try {
        this.widths[item.id] = Math.min(event.target.naturalWidth + 50, 1000)
      } catch (error) {
        this.widths[item.id] = 1000
      }
    },
    handlePreview(item) {
      console.log(item)
      if (item.templatePreview) {
        this.previewSrc = item.templatePreview
        this.previewWidth = this.widths[item.id] || 1000
        this.previewVisible = true
      } else {
        this.$message.error('模板信息加载失败！')
      }
    },
    handleUse(item) {
      this.activeTemplate = item
      getAction('/xghCompanyTemplate/xghCompanyTemplate/info', {}).then((res) => {
        console.log(res)
        if (res.success) {
          let result = res.result || {}
          this.buyInfo = {
            ...result,
            title: '使用模板',
            showType: result.freeCountUsage > 0 ? 1 : 2,
            haveFree: result.freeCount > 0,
            visible: true,
          } //showType 1(有免费次数) 2（购买）3（购买成功）
          //haveFree 是否有免费使用个数

          //没有免费次数先生成订单用于生成支付二维码
          if (result.freeCount == 0 || result.freeCountUsage == 0) {
            this.handleAddOrder(1)
          }
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    handleAddOrder(buyType) {
      console.log(this.activeTemplate)

      //buyType 1买断 2租赁 3免费
      let params = {
        goodsId: this.activeTemplate.id,
        goodsName: this.activeTemplate.name,
        goodsNumber: 1,
        goodsType: '7',
        orderMoney: this.buyInfo.price,
        moduleNumber: 'DYMB',
        buyType,
      }
      console.log(params)

      postAction('/XghAuthorizationCenter/xghAuthorizationCenterOrders/add', params).then((res) => {
        if (res.code == 200) {
          console.log(res)
          this.orderModel = res.result
          if (buyType == 1) {
            this.confirmPay()
          } else {
            this.paySuccess()
          }
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    confirmPay() {
      // 微信支付配置的是晓光的服务，没有配郭哥的，正式用晓光的。
      //
      let signUrl = `http://cloudjinxiaocun.good-software.cn/#/?orderNumber=${this.orderModel.orderNumber}`
      // 本地 环境
      // let signUrl = `http://192.168.2.24:9002/#/?orderNumber=${this.orderModel.orderNumber}`
      // let signUrl = `http://192.168.0.181:9002/#/?orderNumber=${this.orderModel.orderNumber}`

      document.getElementById('qrcode1').innerHTML = ''
      var qrcode = new QRCode(this.$refs.qrCodeUrl1, {
        text: signUrl,
        width: 120,
        height: 120,
        colorDark: '#333333', //二维码颜色
        colorLight: '#ffffff', //二维码背景色
        correctLevel: QRCode.CorrectLevel.H,
      })
      this.checkInterval()
    },
    paySuccess() {
      this.buyInfo.title = '操作确认'
      this.buyInfo.showType = 3
      this.getTableData()
    },
    handleBuyCancel() {
      this.buyInfo.visible = false
      if (this.timer) {
        clearInterval(this.timer)
      }
    },
    checkInterval() {
      this.timer = setInterval(() => {
        this.checkTimeOut(this.timer)
      }, 5000)
    },
    checkTimeOut(timer) {
      const that = this
      setTimeout(() => {
        getAction('/pay/query', { orderNumber: that.orderModel.orderNumber }).then((res) => {
          console.log('查询支付结果', res)
          if (res.success) {
            clearInterval(timer)
            that.showSignModal = false
            let model = res.result[0]
            if (model.goodsType == 7) {
              that.paySuccess()
            }
          }
        })
      }, 0)
    },
    // 获取每页几条数据
    handleSizeChange(val) {
      this.pageSize = val
      this.getTableData()
    },
    // 获取当前第几页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData(val)
    },
    getTableData(val = 1) {
      let params = {
        pageSize: this.pageSize,
        pageNo: val,
        templateSize: this.queryParam.templateSize.replace('全部', ''),
        templateIndustry: this.queryParam.templateIndustry.replace('全部', ''),
        templateType: this.queryParam.templateType.replace('全部', ''),
        templateDesc: this.queryParam.searchValue,
        visibility: 1,
        version: Vue.ls.get('accountVersion')
      }

      getAction('/xghCompanyTemplate/xghCompanyTemplate/list', params).then((res) => {
        if (res.success) {
          if (val == 1) {
            this.currentPage = 1
          }
          this.templateTotal = res.result.total
          this.tableData = res.result.records
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.highLight {
  background-color: #1b94fb;
  border-radius: 5px;
  padding: 4px 10px;
  color: white;
  margin: 10px 0;
}
.template-item {
  // width: 25%;
  min-width: 180px; 
  display: flex;
  justify-content: center;
}
.template-item-content {
  margin: 10px;
  width: 100%;
  // max-width: 330px;
  position: relative;
  // height: 200px;
  // height: 100%;
  border-radius: 10px;
}
.template-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
}
.template-mask {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background-color: rgba($color: #000000, $alpha: 0.5);
  z-index: 2;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 14px;
  padding-bottom: 30px;
}
.template-desc {
  position: absolute;
  padding: 3px 10px;
  left: 0;
  right: 0;
  bottom: 0;
  height: 60px;
  background: white;
  z-index: 3;
  border-radius: 0 0 10px 10px;
  .text {
    overflow: hidden;
    -webkit-line-clamp: 2;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    word-break: break-all;
  }
}
</style>

